<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button type="primary" @click="handleAdd">添加轮播图</el-button>
    </div>
    
    <el-table
      v-loading="loading"
      :data="bannerList"
      border
      style="width: 100%"
      row-key="banId"
    >
      <el-table-column prop="banId" label="ID" width="80" align="center" />
      <el-table-column prop="title" label="标题" min-width="120" />
      <el-table-column label="图片" width="180">
        <template #default="scope">
          <el-image 
            style="width: 150px; height: 80px"
            :src="getImageUrl(scope.row.images)" 
            fit="cover"
            :preview-src-list="[getImageUrl(scope.row.images)]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'info'">
            {{ scope.row.status === '0' ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" width="80" align="center" />
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 轮播图表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="550px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="轮播图标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入轮播图标题" />
        </el-form-item>
        <el-form-item label="图片" prop="images">
          <el-upload
            class="upload-demo"
            action="/api/file/uploadImage/banner"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <el-button type="primary">选择图片</el-button>
            <div class="el-upload__tip">建议上传尺寸: 750px × 350px</div>
          </el-upload>
          <div class="preview" v-if="form.images">
            <img :src="getImageUrl(form.images)" class="preview-image" />
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="上架" value="0" />
            <el-option label="下架" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBannerList, saveOrUpdateBanner, deleteBanner } from '@/api/banner'

// 轮播图列表
const bannerList = ref([])
// 加载状态
const loading = ref(false)
// 提交加载状态
const submitLoading = ref(false)
// 表单对话框可见状态
const dialogVisible = ref(false)
// 表单对话框标题
const dialogTitle = ref('添加轮播图')
// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  banId: null,
  title: '',
  images: '',
  status: '0',
  orderNum: 0
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' }
  ],
  images: [
    { required: true, message: '请上传图片', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  orderNum: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 初始化数据
onMounted(async () => {
  await fetchData()
})

// 获取图片完整URL
const getImageUrl = (path) => {
  if (!path) return ''
  if (path.startsWith('http')) return path
  return `/api/file/download?fileName=${path}`
}

// 获取轮播图列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getBannerList()
    bannerList.value = res.data || []
  } catch (error) {
    console.error('获取轮播图列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理添加轮播图
const handleAdd = () => {
  dialogTitle.value = '添加轮播图'
  // 完全重置表单数据
  form.banId = null
  form.title = ''
  form.images = ''
  form.status = '0'
  form.orderNum = 0
  
  // 延迟调用表单重置，确保DOM已更新
  nextTick(() => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
  })
  
  dialogVisible.value = true
}

// 处理编辑轮播图
const handleEdit = (row) => {
  dialogTitle.value = '编辑轮播图'
  resetForm()
  Object.assign(form, row)
  dialogVisible.value = true
}

// 上传图片前的验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 图片上传成功回调
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    form.images = response.data
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.msg || '图片上传失败')
  }
}

// 处理删除轮播图
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除轮播图 "${row.title}" 吗？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteBanner(row.banId)
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      await fetchData()
    } catch (error) {
      console.error('删除轮播图失败:', error)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 重置表单
const resetForm = () => {
  form.banId = null
  form.title = ''
  form.images = ''
  form.status = '0'
  form.orderNum = 0
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      await saveOrUpdateBanner(form)
      ElMessage({
        type: 'success',
        message: form.banId ? '更新成功!' : '添加成功!'
      })
      dialogVisible.value = false
      await fetchData()
    } catch (error) {
      console.error('保存轮播图失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}
</script>

<style scoped>
.upload-demo {
  margin-bottom: 10px;
}

.preview {
  margin-top: 10px;
}

.preview-image {
  width: 300px;
  height: 150px;
  object-fit: cover;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.el-upload__tip {
  line-height: 1.2;
  margin-top: 8px;
  color: #909399;
}
</style> 